﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Configuration;
using System.Threading;
using System.Net;

namespace ccvmsBendiVideo
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

        }
        /// <summary>
        /// 关键字标签 (默认娱乐)
        /// </summary>
        int tagid = 12;
        /// <summary>
        /// 视频开始ID
        /// </summary>
        int videobeginid = 0;
        /// <summary>
        ///  频道
        /// </summary>
        DataTable pindaodt = new DataTable();
        /// <summary>
        /// 已有标题集合
        /// </summary>
        List<string> titleList = new List<string>();
        /// <summary>
        /// 获取所有标题（数据库ccvms_vodeo表中）
        /// </summary>
        /// <returns></returns>
        private List<string> GetDBvideoName()
        {
            List<string> list = new List<string>();
            try
            {
                var sql = @"select title from  ccvms_video 
union all 
select title from error_title";
                DataTable dt = new CollectLib.Manage().GetDTBySql(sql);
                foreach (DataRow row in dt.Rows)
                {
                    list.Add(row["title"].ToString());
                }
            }
            catch (Exception ex)
            {
                CollectLib.Err.writeInLog(ex.Message);
            }
            return list;
        }

        /// <summary>
        /// 遍历所有文件件中的文件，获取文件名称（未在数据库中的）
        /// </summary>
        /// <returns></returns>
        private List<FileDoc> GetAllFileNames()
        {
            var list = new List<FileDoc>();

            try
            {
                DirectoryInfo theFolder = new DirectoryInfo(ConfigurationManager.AppSettings["videopath"]);
                DirectoryInfo[] dirInfo = theFolder.GetDirectories();

                //遍历文件夹
                foreach (DirectoryInfo NextFolder in dirInfo)
                {
                    // this.listBox1.Items.Add(NextFolder.Name);
                    FileInfo[] fileInfo = NextFolder.GetFiles();

                    foreach (FileInfo NextFile in fileInfo)  //遍历文件
                    {
                        if (!titleList.Contains(NextFile.Name.Substring(0, NextFile.Name.LastIndexOf("."))) && NextFile.Name.IndexOf(".flv") > 0)
                        {
                            FileDoc file = new FileDoc();
                            file.Name = NextFile.Name.Substring(0, NextFile.Name.LastIndexOf("."));
                            file.Path = NextFile.DirectoryName + "\\" + NextFile.Name; ;
                            file.Type = NextFile.DirectoryName.Substring(NextFile.DirectoryName.LastIndexOf("\\") + 1);
                            list.Add(file);
                        }

                    }
                }

            }
            catch (Exception ex)
            {
                CollectLib.Err.writeInLog(ex.Message);
                list = new List<FileDoc>();
            }
            return list;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            var list = GetAllFileNames();//所有文件
            this.progressBar1.Value = 0;
            this.progressBar1.Maximum = list.Count;
            foreach (FileDoc doc in list)
            {

                try
                {
                    this.progressBar1.Value = this.progressBar1.Value + 1;
                    var videotype = 8;//引用类型，
                    var time = getTime();


                    var videourl = doc.Path.Replace(@"\", @"/").Replace(ConfigurationManager.AppSettings["webdizhi"], ConfigurationManager.AppSettings["webname"]);

                    var videodesc = doc.Name;

                    var videotitle = doc.Name;

                    var videoimg = GetImgPath(doc.Name);

                    videobeginid++;
                    int pindaoid = 0; ;

                    foreach (DataRow dr in pindaodt.Rows)
                    {
                        if (dr["pindaoname"].ToString() == doc.Type)
                        {
                            pindaoid = Convert.ToInt32(dr["pindaoid"].ToString());
                            tagid = pindaoid;// GetTagidbyPindaoid(pindaoid); //获取频道对应的tagid 
                            break;
                        }
                    }

                    var sql = @"insert into ccvms_video(uid,username,cid,type,title,videourl,createtime,description,uploadpic,pictype)
                            values(?uid,?username,?cid,?type,?title,?videourl,?createtime,?description,?uploadpic,?pictype)";

                    string[] param1 ={"?uid","?username","?cid","?type","?title","?videourl",
                    "?createtime","?description","?uploadpic","?pictype" };
                    object[] value1 = { 2, "admin", pindaoid, videotype, videotitle, videourl, time, videodesc, videoimg, 2 };
                    var id = 0;
                    try
                    {
                        id = new CollectLib.Manage().ExecSqlAndReturnID(sql, param1, value1);
                        sql = "insert into ccvms_videotag(vid,tagid) values(?vid,?tagid)";
                        string[] param2 = { "?vid", "?tagid" };
                        object[] value2 = { videobeginid, tagid };
                        new CollectLib.Manage().ExecuteUpdate(sql, param2, value2);
                        Thread.Sleep(1000);
                    }
                    catch (Exception ex)
                    {
                        CollectLib.Err.writeInLog(ex.Message);
                        break;
                    }

                }
                catch (Exception ex)
                {
                    Thread.Sleep(5000);
                    CollectLib.Err.writeInLog(doc.Name + "," + doc.Path + "," + ex.Message);
                    continue;

                }

            }

        }

        private string GetImgPath(string imgname)
        {
            #region 下载图片，重命名，并自动上传至服务器，
            var videoimg = string.Empty;
            try
            {
                //根据图片名称获取图片地址
                var videoimghtml = new CollectLib.Manage().GetHtmlCode(string.Format("http://www.soku.com/search_video/q_{0}", imgname));


                videoimg = GetVideoImgByhtml(videoimghtml, imgname);

                var wc = new WebClient();
                var preStr = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                preStr = preStr + ".jpg";//生成图片名称
                //下载的图片存储在文件夹中
                wc.DownloadFile(videoimg, preStr);
                videoimg = "video/" + (DateTime.Now.Month < 10
                               ? DateTime.Now.Year + "0" + DateTime.Now.Month + "/" + preStr
                               : DateTime.Now.Year.ToString() + DateTime.Now.Month + "/" + preStr);
                File.Copy(preStr, ConfigurationManager.AppSettings["imgAddress"] + (DateTime.Now.Month < 10
                               ? DateTime.Now.Year + "0" + DateTime.Now.Month + "/" + preStr
                               : DateTime.Now.Year.ToString() + DateTime.Now.Month + "/" + preStr));
                File.Delete(preStr);


            }
            catch (Exception ex)
            {
                CollectLib.Err.writeInLog("GetImgPath 方法" + ex.Message);
                if (ex.Message.IndexOf("StartIndex cannot be less than zero") >= 0)
                {
                    var sql = string.Format("insert into error_title(title,type) values('{0}',1)", imgname);
                    new CollectLib.Manage().ExecuteSql(sql);
                }
                throw ex;
            }
            return videoimg;
            #endregion
        }

        private string GetVideoImgByhtml(string videoimghtml, string title)
        {
            var indexbeg = 0;
            var indexend = 0;
            for (int i = 0; i < 20; i++)
            {
                videoimghtml = videoimghtml.Substring(videoimghtml.IndexOf("<img alt=\""));
                videoimghtml = videoimghtml.Substring(10);
                var name = videoimghtml.Substring(0, videoimghtml.IndexOf("\" src="));
                if (name == title)
                {
                    break;
                }
            }
            indexbeg = videoimghtml.IndexOf("http://");
            indexend = videoimghtml.IndexOf("\" onerror");
            return videoimghtml.Substring(indexbeg, indexend - indexbeg);

        }
        private int GetTagidbyPindaoid(int pindaoid)
        {
            string sql = string.Format(@"select tagid from ccvms_videotag as a,ccvms_video as b where a.vid=b.vid and b.cid={0} LIMIT 0 , 1", pindaoid);
            DataTable pindaodt = new CollectLib.Manage().GetDTBySql(sql);
            if (pindaodt.Rows.Count != 1)
            {
                MessageBox.Show("频道对应关键字未找到");
                return 1;
            }
            return Convert.ToInt32(pindaodt.Rows[0]["tagid"]);
        }
        /// <summary>
        /// 获取数据库频道
        /// </summary>
        private void LoadPindaoDt()
        {
            try
            {

                string sql = "select cid as pindaoid,htmlpath as pindaoname,description from ccvms_channel ";
                pindaodt = new CollectLib.Manage().GetDTBySql(sql);
            }
            catch (Exception ex)
            {
                CollectLib.Err.writeInLog(ex.Message);
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            LoadPindaoDt();
            titleList = GetDBvideoName();
            SetvVideoBeginID();
            var list = GetAllFileNames();
            label1.Text = string.Format("频道个数{0}\n 视频个数{1}\n 计划新增个数{3}\n 视频开始ID:{2} ", pindaodt.Rows.Count, titleList.Count, videobeginid, list.Count);
            label1.Text += string.Format("第一个计划加入视频：{0}", list[0].Name);
        }
        /// <summary>
        /// 将开始时间转换成INT型。tosring
        /// </summary>
        private string getTime()
        {
            var start = DateTime.Now;
            var result = 0;
            var startdate = new DateTime(1970, 1, 1, 8, 0, 0);
            var seconds = start - startdate;
            result = Convert.ToInt32(seconds.TotalSeconds);
            return result.ToString();
        }
        /// <summary>
        /// 最大ID
        /// </summary>
        private void SetvVideoBeginID()
        {
            var sql = "select max(vid) from ccvms_video";
            var dt = new CollectLib.Manage().GetDTBySql(sql);
            if (dt.Rows.Count != 1)
                throw new ApplicationException("开始id异常");
            videobeginid = int.Parse(dt.Rows[0][0].ToString());
        }
    }
    public class FileDoc
    {
        string name;
        public string Name
        {
            get { return name; }
            set { name = value; }
        }
        string path;
        public string Path
        {
            get { return path; }
            set { path = value; }
        }
        string type;
        public string Type
        {
            get { return type; }
            set { type = value; }
        }
    }
}
